﻿/****************************************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (http://rapidwebdev.org)
	Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@RapidWebDev.org

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************************************/

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaoJianSoft.Common;
using BaoJianSoft.RapidWeb;
using BaoJianSoft.RapidWeb.DynamicPages.Configurations;
using MyControls = BaoJianSoft.RapidWeb.Controls;

namespace BaoJianSoft.Platform.Web.Controls
{
	/// <summary>
	/// Hierarchy selector web control.
	/// </summary>
	[ToolboxData("<{0}:HierarchySelector runat=\"server\"/>")]
	public class HierarchySelector : System.Web.UI.WebControls.WebControl, INamingContainer, IPostBackDataHandler, ITextControl
	{
		private static IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
		private static IHierarchyApi hierarchyApi = SpringContext.Current.GetObject<IHierarchyApi>();
		private MyControls.ComboBox comboBox;
		private HierarchyDataObject selectedHierarchy;

		/// <summary>
		/// Sets/gets max items rendered as selection candidate, defaults to 25.
		/// </summary>
		public int MaxItemCount
		{
			get { if (base.ViewState["MaxItemCount"] == null) return 25; return (int)base.ViewState["MaxItemCount"]; }
			set { base.ViewState["MaxItemCount"] = value; }
		}

		/// <summary>
		/// Sets/gets hierarchy type which the control works for. The property is required for a valid hierarchy type identifier.
		/// </summary>
		public string HierarchyType { get; set; }

		/// <summary>
		/// Sets/gets client event which will be fired when the selected item changed. 
		/// The signature of javascript callback method should be as: "function MethodName(string newValue, string oldValue) { }"
		/// </summary>
		public string OnClientSelectedItemChanged
		{
			get
			{
				if (Kit.IsEmpty(base.ViewState["OnClientSelectedItemChanged"])) return "null";
				return base.ViewState["OnClientSelectedItemChanged"] as string;
			}
			set { base.ViewState["OnClientSelectedItemChanged"] = value; }
		}

		/// <summary>
		/// Sets/gets selected hierarchy instance.
		/// </summary>
		public HierarchyDataObject SelectedHierarchy
		{
			get { return this.selectedHierarchy; }
			set { this.selectedHierarchy = value; }
		}

		/// <summary>
		/// Text of the control.
		/// </summary>
		public string Text
		{
			get 
			{
				if (this.selectedHierarchy != null) return this.selectedHierarchy.Name;
				return null;
			}
			set { }
		}

		/// <summary>
		/// Raises the System.Web.UI.Control.Load event.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			this.Page.RegisterRequiresPostBack(this);
		}

		/// <summary>
		/// Called by the ASP.NET page framework to notify server controls that use composition-based 
		/// implementation to create any child controls they contain in preparation for posting back or rendering.
		/// </summary>
		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			this.comboBox = new MyControls.ComboBox
			{
				ID = "ComboBox",
				TextField = "Name",
				ValueField = "Id",
				MinChars = 1,
				Mode = MyControls.ComboBoxDataSourceModes.Remote,
				QueryParam = "q",
				Proxy = DataProxyTypes.HttpProxy,
				Url = WebUtility.ResolveAbsoluteUrl("Services/HierarchyService.svc/json/FindByKeyword"),
				Enabled = this.Enabled,
				SelectedItemChangedCallback = this.OnClientSelectedItemChanged
			};

			this.comboBox.Params = new Collection<ComboBoxDynamicDataSourceParamConfiguration> 
			{
				new ComboBoxDynamicDataSourceParamConfiguration("start") { Value = "0" },
				new ComboBoxDynamicDataSourceParamConfiguration("limit") { Value = this.MaxItemCount.ToString() },
				new ComboBoxDynamicDataSourceParamConfiguration("sortfield") { Value = "Name" },
				new ComboBoxDynamicDataSourceParamConfiguration("sortDirection") { Value = "ASC" },
			};

			this.Controls.Add(this.comboBox);
		}

		/// <summary>
		/// Raises the System.Web.UI.Control.PreRender event.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (string.IsNullOrEmpty(this.HierarchyType))
				throw new InvalidProgramException("The property \"HierarchyType\" of HierarchySelector control is not specified.");

			this.comboBox.Params.Add(new ComboBoxDynamicDataSourceParamConfiguration("hierarchyType") { Value = this.HierarchyType });

			if (this.selectedHierarchy != null)
			{
				this.comboBox.Items.Clear();
				this.comboBox.Items.Add(new ListItem(this.selectedHierarchy.Name, this.selectedHierarchy.Id.ToString()));
				this.comboBox.SelectedValue = this.selectedHierarchy.Id.ToString();
				this.comboBox.SelectedText = this.selectedHierarchy.Name;
			}
		}

		#region IPostBackDataHandler Members

		bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
		{
			string comboboxKey = string.Format(CultureInfo.InvariantCulture, "{0}$ComboBox", postDataKey);
			string selectedItemValue = postCollection[comboboxKey];
			if(!string.IsNullOrEmpty(selectedItemValue))
			{
				Guid hierarchyId = new Guid(selectedItemValue);
				this.selectedHierarchy = hierarchyApi.GetHierarchyData(hierarchyId);
			}

			return true;
		}

		void IPostBackDataHandler.RaisePostDataChangedEvent()
		{
			
		}

		#endregion
	}
}

